using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Student1.Models;

namespace Student1.Controllers;

public class StudentsController : Controller
{
    // 引用数据库上下文
    private readonly StudentDbContext _db;
    // 创建一个无参的构造方法
    public  StudentsController()
    {
        _db=new StudentDbContext();
    }
    //查询    
    public IActionResult Index(string KeyWord)
    {
        KeyWord=string.IsNullOrEmpty(KeyWord)?"":KeyWord.Trim();
        if(string.IsNullOrEmpty(KeyWord))
        {
            var list=_db.Students.ToList();
            return View(list);
        }
        var a=_db.Students.Where(x=>x.Name.Contains(KeyWord)).ToList();
        return View(a);
    }

    // 增加
      public IActionResult Add()
      {
        return View();
      }

    [HttpPost]      
      public IActionResult Add(Student input)
      {
        _db.Students.Add(input);
        // SaveChanges(保存更改：Save changes → SaveChanges)
        _db.SaveChanges();
        return RedirectToAction("Index");
      }

    // 删除 
    public IActionResult Delete(int id)
      {
        //First(第一个)Or(或者)Default(默认)
        var a=_db.Students.FirstOrDefault(x=>x.Id==id);
        return View(a);
      }

    public IActionResult Deletes(int id)
      {
        //First(第一个)Or(或者)Default(默认)
        var a=_db.Students.FirstOrDefault(x=>x.Id==id);
        if(a==null)
        {
            //NotFound(找不到:not found → NotFound)
            return NotFound();
        }
        _db.Students.Remove(a);
        _db.SaveChanges();

        return RedirectToAction("Index");
      }
    // 修改
     public IActionResult Edit(int id)
      {
        //First(第一个)Or(或者)Default(默认)
        var a=_db.Students.FirstOrDefault(x=>x.Id==id);
        return View(a);
      }

      [HttpPost]
     public IActionResult Edit(Student input)
      {
        //First(第一个)Or(或者)Default(默认)
        var a=_db.Students.FirstOrDefault(x=>x.Id==input.Id);
        if(a==null)
        {
            //NotFound(找不到:not found → NotFound)
            return NotFound();
        }
        a.Name=input.Name;
        a.Sex=input.Sex;
        a.Age=input.Age;
        _db.SaveChanges();
        return RedirectToAction("Index");
      }
      
}